<?

class JqaxHelper extends Helper {

    var $helpers = array("Html");

    /**
     * Generates AJAX link
     *
     * @param string $text - link title
     * @param string $url - URL
     * @param string $target - target div to put response (example: "#myDiv")
     * @param string $data - Id of element with data to be send (example "#myForm")
     * @param Array() $options - JQuery options
     * @param Array() $attr - HTML attributes
     * @param string $confirm - Confirm string
     * @param string $loader - image file with loader animation
     */
    function link($text, $url, $target = null, $data = null, $options = null, $attr = null, $confirm = null, $loading = null)
    {
    	$aId = 'link' . intval(rand());
    	$url = $this->Html->url($url);
    	$att = '';
    	if (is_array($attr))
    	{
            foreach($attr as $k=>$v)
            {
                $att .= $k.'="'.$v.'" ';
            }
        }
        $code = $this->_getCode($url, $target, $data, $options, $loading);
		$r = "<a href=\"$url\" id=\"$aId\" ".$att.">$text</a>";
		if(!empty($confirm))
			$r .= $this->_jsBlock($this->_addReady("\$(\"#$aId\").click(function(){ if (confirm(\"".addslashes($confirm)."\")){ $code } ;return false;})"));
		else
			$r .= $this->_jsBlock($this->_addReady("\$(\"#$aId\").click(function(){ $code ;return false;})"));
		return $r;
    }

    function button($text, $url, $target = null, $data = null, $options = null, $attr = null, $confirm = null, $loading = null)
    {
    	$aId = 'link' . intval(rand());
    	$url = $this->Html->url($url);
    	$att = '';
    	if (is_array($attr))
    	{
            foreach($attr as $k=>$v)
            {
                $att .= $k.'="'.$v.'" ';
            }
        }
        $code = '';
        if (!empty($options['beforeAjax']))
        {
        	$code .= $options['beforeAjax'];
        	unset($options['beforeAjax']);
        }
        $code .= $this->_getCode($url, $target, $data, $options, $loading);
		$r = "<button type=\"button\" id=\"$aId\" ".$att.">$text</button>";
		if(!empty($confirm))
			$r .= $this->_jsBlock($this->_addReady("\$(\"#$aId\").click(function(){ if (confirm(\"".addslashes($confirm)."\")){ $code };return false;})"));
		else
			$r .= $this->_jsBlock($this->_addReady("\$(\"#$aId\").click(function(){ $code ;return false;})"));
		return $r;
    }

    function inputButton($text, $url, $target = null, $data = null, $options = null, $attr = null, $confirm = null, $loading = null)
    {
    	$aId = 'link' . intval(rand());
    	$url = $this->Html->url($url);
    	$att = '';
    	if (is_array($attr))
    	{
            foreach($attr as $k=>$v)
            {
                $att .= $k.'="'.$v.'" ';
            }
        }
        $code = '';
        if (!empty($options['beforeAjax']))
        {
        	$code .= $options['beforeAjax'];
        	unset($options['beforeAjax']);
        }
        $code .= $this->_getCode($url, $target, $data, $options, $loading);
		$r = "<input type=\"button\" id=\"{$aId}\" {$att} value=\"{$text}\" />";
		if(!empty($confirm))
			$r .= $this->_jsBlock($this->_addReady("\$(\"#$aId\").click(function(){ if (confirm(\"".addslashes($confirm)."\")){ $code };return false;})"));
		else
			$r .= $this->_jsBlock($this->_addReady("\$(\"#$aId\").click(function(){ $code ;return false;})"));
		return $r;
    }

    function _getCode($url, $target = null, $data = null, $options = null, $loading = null)
    {
    	$code = "$.ajax({";
    	$code .= "type: 'POST',";
    	$code .= "url: '{$url}',";
    	if (!empty($data)) {
    	    if (is_array($data)) {
    	        $js_data = '';
    	        foreach ($data as $k => $v) {
    	            $v = addslashes(strval($v));
                    $js_data .= "{$k}:'$v',";
    	        }
    	        if (strlen($js_data)) {
    	            $js_data = substr($js_data, 0, strlen($js_data)-1);
                    $code .= "data: {{$js_data}},";
    	        }
    	    } else {
                $code .= "data: $('{$data}').serialize(),";
    	    }
            $code .= "dataType: 'html',";
    	}
	   	$code .= "success: function(data){";
	   	if (!empty($target)) {
			$code .= '$("'.$target.'").html(data);';
	   	}
		if (!empty($options['success'])) {
			$code .= $options['success'].';';
		}
	   	$code .= "},";
	   	$code .= "beforeSend: function(data){";
	   	if (!empty($loading)) {
	   	    $bef = '<center>';
	   	    $aft = '</center>';
            if (!empty($options['no-center'])) {
    	   	    $bef = $aft = '';
            }
	   		$code .= '$("'.$target.'").html("'.$bef.addslashes($loading).$aft.'");';
	   	}
	   	$code .= ((!empty($options['beforeSend']))? $options['beforeSend'] : '');
	   	$code .= "}";
	   	$code .= "});";
		return $code;
    }

    function code($url, $target = null, $data = null, $options = null, $loading = null)
    {
    	$url = $this->Html->url($url);
    	$code = $this->_getCode($url, $target, $data, $options, $loading);
		return $code;
    }

    function toggleLink($text, $target)
    {
    	return "<a href=\"#\" onclick=\"$('".$target."').toggle()\">$text</a>";
    }

/*    function observeField($element, $options){
        $event = $options["event"];
        $update = $options["update"];
        $url = $this->Html->url($options["url"]);


        $code = $options["loading"].'
        $.ajax({
   type: "POST",
   url: "'.$url.'",
   data: $("'.$element.'").serialize(),
   success: function(data){
        $("'.$update.'").html(data);
       '.$options["complete"].'
   }
 });
    ';

        return $this->_jsBlock($this->_addReady("\$(\"$element\").$event(function(){ $code })"));
    }

    function observeForm($element, $options){
        $event = $options["event"];
        $update = $options["update"];
        $url = $this->Html->url($options["url"]);


        $code = '$("'.$element.'").ajaxSubmit({
            target:        \''.$update.'\',
            beforeSubmit:  function(){'.$options["loading"].'},
            success:       function(){'.$options["complete"].'}
            }
        );';

        return $this->_jsBlock($this->_addReady("\$(\"$element\").$event(function(){ $code return false; })"));
    }*/

    function _jsBlock($content){
        return "<script type=\"text/javascript\">$content</script>";
    }
    function _addReady($content){
        return "\$(function(){ $content } );";
    }

    function test(){
        echo $this->_jsBlock($this->_addReady("alert(\"Jax Helper has been installed and ready to use!\");"));
    }
}
?>